/**
 * Computer Network, Programming Assignment #2
 * 
 * gSocket Class
 * 
 * Utilities used for clients to connect to the grid for sending/listening
 * 
 * @author Yancheng Li
 *
 */

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;


public class gSocket {
	
	// connect to a grid for sending packets
	public static Socket connectTo(Point pos){
		int port = PGPeer.calInPort(pos);
		
		Socket peerSocket = null;
		try {
			peerSocket = new Socket("localhost", port);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return peerSocket;
	}
	
	// send a packet through the socket
	public static void sendPacket(Socket socket, int x, int y, int port, char[] data){
		GPDatagram packet = new GPDatagram(x, y, port, data);
		try {
			DataOutputStream out = 				
				new DataOutputStream(socket.getOutputStream());
			
			byte[] byteData = PSPUtil.convert2Byte(packet.getRawdata());
			out.write(byteData);
			//out.close();
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	// connect to a grid to listen to a specific port
	public static Socket listenTo(Point pos, int listenPort){
		int port = PGPeer.calOutPort(pos);
		
		Socket receiveSocket = null;
		try {
			receiveSocket = new Socket("localhost", port);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		char[] numHex = Integer.toHexString(listenPort).toCharArray();
		char[] digitNum = new char[4];
		
		//length
		for(int i = 0; i < 4; i++)
			digitNum[i] = '0';
		for(int i = numHex.length - 1, j = 3; i >= 0; i--, j--){
			digitNum[j] = numHex[i];
		}
		
		try {
			DataOutputStream out = 				
				new DataOutputStream(receiveSocket.getOutputStream());
			
			byte[] byteData = PSPUtil.convert2Byte(digitNum);
			out.write(byteData);
			//out.close();
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return receiveSocket;
	}
	
}
